// pages/sys/repair/repair.js

const app = getApp() // 获取应用实例
const uploadImage = require('../../../utils/upload');
const util = require('../../../utils/util')
import { getRepairList, postAddRepair } from '../../../utils/http/api'

Page({

    data: {
        // tab切换 
        currentTab: 0,
        // 报修描述hint
        desc_holder: '请写下您的报修内容，有助于我们工作人员快速解决问题。',
        // 报修类型
        repair_type: ['水管故障', '电器故障', '门窗故障', '墙面故障', '地面故障', '其他问题'],
        // 报修类型的索引
        repair_index: 0,
        // 跳转到我的房间页面获取到的房间信息
        currRoom: {},
        // desc 记录报修描述
        desc: '',
        // 记录点击的图片索引
        img_index: 0,
        // 选择的图片列表
        img_list: ['', '', ''],
        // 联系手机号
        phone: '',
        // 报修记录列表
        repair_list: [],
    },

    // 切换导航
    swichNav(e) {
        var that = this
        if (this.data.currentTab === e.target.dataset.current) {
            return false
        } else {
            that.setData({ currentTab: e.target.dataset.current, })
        }
    },

    // 滑动切换
    swiperChange: function (e) {
        this.setData({ currentTab: e.detail.current, })
    },

    // 报修类型picker
    onPickerChange: function (e) {
        let that = this;
        that.setData({ repair_index: e.detail.value, })
    },

    // 点击选择门面号码
    onRoomNum(e) {
        // 跳转到我的房间页面获取房间信息
        util.navigateTo('/pages/charge/house/my_house/my_house?from=1')
    },

    // 监听输入的报修描述
    onInput(e) {
        this.setData({ desc: e.detail.value })
    },

    // onInputPhone
    onInputPhone(e) {
        this.setData({ phone: e.detail.value })
    },

    // 点击第1张图
    onImg1(e) {
        this.setData({ img_index: 0 })
        this.chooseimage()
    },

    // 点击第2张图
    onImg2(e) {
        this.setData({ img_index: 1 })
        this.chooseimage()
    },

    // 点击第3张图
    onImg3(e) {
        this.setData({ img_index: 2 })
        this.chooseimage()
    },

    // 原生弹窗选择图片或拍照
    chooseimage() {
        var that = this
        wx.showActionSheet({
            // alertText: '选择图片',
            itemList: ['从相册中选择', '拍照'],
            itemColor: "#000",
            success: function (res) {
                if (!res.cancel) {
                    if (res.tapIndex == 0) {
                        that.chooseWxImage('album')
                    } else if (res.tapIndex == 1) {
                        that.chooseWxImage('camera')
                    }
                }
            }
        })
    },

    // 微信选择图片或拍照
    chooseWxImage(type) {
        var that = this;
        wx.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: [type],
            success(res) {
                console.log(res);
                wx.showLoading({ title: '图片上传中...', mask: true })
                // applyrefund 则为bucket下的文件夹路径 可根据自身需求进行分类
                uploadImage(res.tempFilePaths[0], 'wuye/mp/',
                    function (res) {
                        wx.hideLoading();
                        console.log("上传成功结果 = ", res)
                        // that.data.img_list.push(imgPath);// 追加图片地址
                        that.data.img_list[that.data.img_index] = res// 为指定下标的图片设置上传OSS后的url地址的值
                        console.log(that.data.img_list)
                        that.setData({ img_list: that.data.img_list })// 刷新数据
                    },
                    function (res) {
                        wx.hideLoading()
                        console.log("上传失败。。")
                        console.log(res)
                    }
                )

            },

            fail(res) {
                wx.showToast({ title: '选择图片异常', icon: 'none' })
            }

        })
    },

    // 请求报修记录列表
    async reqRepairList() {
        wx.showLoading({ title: '处理中', mask: true, })
        let { code, msg, data } = await getRepairList({ page: '1', limit: '999999', token: app.gl.token })
        console.log(`reqRepairList...code=${code},msg=${msg},data=`, data)
        wx.stopPullDownRefresh()
        if (code == '1') {
            this.setData({ repair_list: data.data })
        } else {
            wx.showToast({ title: msg, icon: 'error' })
        }
    },

    // 请求添加报修
    reqAddRepair() {
        let that = this;
        let repType = this.data.repair_type[this.data.repair_index];// 报修类型
        if (util.isNull(repType)) {
            wx.showToast({ title: '请选择报修类型', icon: 'none' })
            return
        }
        let roomId = this.data.currRoom.id
        if (util.isNull(roomId)) {
            wx.showToast({ title: '请选择房间', icon: 'none' })
            return
        }
        if (util.isNull(this.data.desc)) {
            wx.showToast({ title: '请输入报修描述', icon: 'none' })
            return
        }
        if (util.isNull(this.data.phone)) {
            wx.showToast({ title: '请输入联系电话', icon: 'none' })
            return;
        }
        let imgStr = '';
        for (let i = 0; i < this.data.img_list.length; i++) {
            let url = this.data.img_list[i];
            if (!util.isNull(url)) {
                imgStr += ','
                imgStr += url
            }
        }
        if (!util.isNull(imgStr) && imgStr.startsWith(',')) {
            imgStr = imgStr.substring(1)
        }
        console.log('imgStr = ' + imgStr)

        wx.showModal({
            title: '提示',
            content: '是提交该报修？',
            async success(res) {
                if (res.confirm) {// 点击确定
                    wx.showLoading({ title: '处理中', mask: true, })
                    // let token = util.isLogin()
                    let { code, msg, data } = await postAddRepair({
                        token: app.gl.token, community_code: roomId, device_name: repType, desc: that.data.desc, image: imgStr, mobile: that.data.phone
                    })
                    console.log(`postAddRepair...code=${code},msg=${msg},data=`, data)
                    wx.stopPullDownRefresh()
                    if (code == '1') {
                        wx.showModal({
                            title: '提示', content: msg, showCancel: false,
                            success(res) {
                                if (res.confirm) { wx.navigateBack() }
                            }
                        })
                    } else {
                        wx.showToast({ title: msg, icon: 'error' })
                    }

                } else if (res.cancel) {// 点击取消

                }
            }
        })
    },

    // 微信社区demo：上传图片
    uploadImg() {
        let that = this;
        wx.chooseImage({
            count: 1, //处理图片上传数量 （可根据自身需求配置）
            success: function (res) {
                wx.showLoading({ title: '上传中...', mask: true })
                // applyrefund 则为bucket下的文件夹路径 可根据自身需求进行分类
                uploadImage(res.tempFilePaths[0], 'wuye/mp/',
                    function (res) {
                        wx.hideLoading();
                        console.log("上传成功结果 = ");
                        console.log(res);
                    },
                    function (res) {
                        wx.hideLoading();
                        console.log("上传失败。。");
                    }
                )
            }
        })
    },

    // 生命周期函数--监听页面加载
    onLoad: function (options) {
        let mobile = wx.getStorageSync('mobile')
        this.setData({ phone: mobile })
        this.reqRepairList()
    },

    // 点击拍照
    onCamera(e) {
        let camera = wx.createCameraContext()
        camera.takePhoto({
            quality: 'low',
            success(res) { console.log(res.tempImagePath) },
            fail(res) { console.log('拍照失败') }
        })
    },

    // 点击选择图片
    onSelImg(e) {
        wx.showToast({ title: '选择图片', icon: 'none' })
    },

    // 点击取消
    onCancel(e) {
        this.hideModal()
    },

    //点击我显示底部弹出框
    clickme() {
        this.showModal()
    },

    // 显示对话框
    showModal() {
        // 显示遮罩层
        var animation = wx.createAnimation({ duration: 200, timingFunction: "linear", delay: 0 })
        this.animation = animation
        animation.translateY(300).step()
        this.setData({ animationData: animation.export(), showModalStatus: true })
        setTimeout(function () {
            animation.translateY(0).step()
            this.setData({ animationData: animation.export() })
        }.bind(this), 200)
    },

    // 隐藏对话框
    hideModal() {
        // 隐藏遮罩层
        var animation = wx.createAnimation({
            duration: 200,
            timingFunction: "linear",
            delay: 0
        })
        this.animation = animation
        animation.translateY(300).step()
        this.setData({
            animationData: animation.export(),
        })
        setTimeout(function () {
            animation.translateY(0).step()
            this.setData({
                animationData: animation.export(),
                showModalStatus: false
            })
        }.bind(this), 200)
    },

})